package com.yvon.grpc.client.service;

import com.yvon.grpc.api.HelloWorldGrpc;
import com.yvon.grpc.api.Ip;
import com.yvon.grpc.api.Name;
import com.yvon.grpc.api.NameServersGrpc;
import io.grpc.ManagedChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author : wangyufeng
 * @since : 2021-10-19
 */
@Service
public class NameServersClientService {

    private NameServersGrpc.NameServersBlockingStub stub;

    @Autowired
    private ManagedChannel managedChannel;

    @PostConstruct
    private void init() {
        stub = NameServersGrpc.newBlockingStub(managedChannel);
    }

    public List<Ip> getIpsByName(String n) {
        List<Ip> result = new ArrayList<Ip>();

        Name name = Name.newBuilder().setName(n).build();

        Iterator<Ip> iterator = stub.getIpByName(name);

        while (iterator.hasNext()){

            result.add(iterator.next());

        }
        return result;
    }
}
